#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:    御风
# @Mail:      zhong.yufeng@foxmail.com
# @Time:      2022/4/12 5:10


import json
import config
from flask import request, current_app as app
from flask_cors import cross_origin
from sqlalchemy.exc import InternalError
from modules.product import ProductDataBase
from utils.helper import md5
from utils.result import ApiResult
from utils.session.session import Session
from .goods import route


def productQuery():
    try:
        keywords = request.args.get("keywords", "", str).strip()
        areaId = request.args.get("areaId", 0, int)
        categoryId = request.args.get("categoryId", 0, int)
        pageNum = request.args.get("pageNum", 1, int)
        pageSize = request.args.get("pageSize", 20, int)
    except Exception:
        return ApiResult.error(203001, msg="参数有误")

    try:
        if keywords == "":
            cacheKey = f"product_null_{areaId}_{categoryId}_{pageNum}_{pageSize}"
        else:
            cacheKey = f"product_{md5(keywords)}_{areaId}_{categoryId}_{pageNum}_{pageSize}"
        try:
            data = app.cache.get(cacheKey)
        except Exception:
            data = None
        if data is None:
            db = ProductDataBase()
            data = db.query(keywords, areaId, categoryId, pageNum, pageSize)
            if data.get("items"):
                app.cache.set(cacheKey, data, timeout=config.CACHE_TIMEOUT)

    except ValueError as e:
        return ApiResult.error(203002, msg=str(e))
    except InternalError as e:
        app.logger.error(f"[数据库] {e}")
        return ApiResult.error(203003, msg="失败")
    except Exception as e:
        app.logger.error(f"[错误] {e}")
        return ApiResult.error(203004, msg="失败")

    return ApiResult.success(data, msg="成功")


def productInsert():
    try:
        session = Session.get()
        adminAccount = session.get("adminAccount", None)
        content = request.get_data(cache=False)
        if not content or content == "" or content == b"":
            raise ValueError("提交数据为空")
        try:
            content = json.loads(content, encoding="utf-8")
        except Exception:
            content = None
        if not content or not isinstance(content, list):
            raise ValueError("提交数据格式错误")
    except ValueError as e:
        return ApiResult.error(204001, msg=str(e))
    except Exception:
        return ApiResult.error(204002, msg="失败")

    try:
        db = ProductDataBase()
        result = db.insert(content, adminAccount)
    except ValueError as e:
        return ApiResult.error(204003, msg=str(e))
    except InternalError as e:
        app.logger.error(f"[数据库] {e}")
        return ApiResult.error(204004, msg="失败")
    except Exception as e:
        app.logger.error(f"[错误] {e}")
        return ApiResult.error(204005, msg="失败")

    if not result:
        return ApiResult.error(204006, msg="插入失败")
    return ApiResult.success(result, msg="成功")


def productDelete():
    try:
        arg = request.args.get("productId", "", str)
        pids = []
        if arg is not None and arg != "":
            for pid in arg.split(","):
                pid = pid.strip()
                if pid == "":
                    continue
                if not pid.isdigit():
                    raise ValueError("商品 ID 值异常")
                pids.append(pid)
        if not pids:
            raise ValueError("商品 ID 不能为空")
    except ValueError as e:
        return ApiResult.error(205001, msg=str(e))
    except Exception:
        return ApiResult.error(205002, msg="失败")

    try:
        db = ProductDataBase()
        result = db.delete(pids)
    except ValueError as e:
        return ApiResult.error(205003, msg=str(e))
    except InternalError as e:
        app.logger.error(f"[数据库] {e}")
        return ApiResult.error(205004, msg="失败")
    except Exception as e:
        app.logger.error(f"[错误] {e}")
        return ApiResult.error(205005, msg="失败")

    if not result:
        return ApiResult.error(205006, msg="删除失败")
    return ApiResult.success(result, msg="成功")


def productUpdate():
    try:
        session = Session.get()
        adminAccount = session.get("adminAccount", None)
        productId = request.args.get("productId", "", str)
        if not productId or productId == "":
            raise ValueError("商品 ID 不能为空")
        if not productId.isdigit():
            raise ValueError("商品 ID 值异常")
        content = request.get_data(cache=False)
        if not content or content == "" or content == b"":
            raise ValueError("提交数据为空")
        try:
            content = json.loads(content, encoding="utf-8")
        except Exception:
            content = None
        if not content or not isinstance(content, dict):
            raise ValueError("提交数据格式错误")
    except ValueError as e:
        return ApiResult.error(206001, msg=str(e))
    except Exception:
        return ApiResult.error(206002, msg="失败")

    try:
        db = ProductDataBase()
        result = db.update(productId, content, adminAccount)
    except ValueError as e:
        return ApiResult.error(206003, msg=str(e))
    except InternalError as e:
        app.logger.error(f"[数据库] {e}")
        return ApiResult.error(206004, msg="失败")
    except Exception as e:
        app.logger.error(f"[错误] {e}")
        return ApiResult.error(206005, msg="失败")

    if not result:
        return ApiResult.error(206006, msg="更新失败")
    return ApiResult.success(result, msg="成功")


# http://127.0.0.1:9001/goods/product
@route.route(r"/product", methods=["GET", "POST", "DELETE", "PUT"], strict_slashes=False)
@cross_origin()
def apiProduct():
    """
    商品信息
    """

    # 查询
    if request.method == "GET":
        return productQuery()
    # 新增
    elif request.method == "POST":
        return productInsert()
    # 删除
    elif request.method == "DELETE":
        return productDelete()
    # 修改
    elif request.method == "PUT":
        return productUpdate()
    else:
        abort(405)
        return
